package com.wzdigit.wms.wms.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

/**
 * 任务调度配置
 * @author Administrator
 *
 */
@Component
@EnableScheduling
@Slf4j
public class DefaultSchedulingConfigurer implements SchedulingConfigurer {

	private ScheduledTaskRegistrar taskRegistrar;

	private Map<Integer, ScheduledFuture<?>> taskFutures = new ConcurrentHashMap<Integer, ScheduledFuture<?>>();

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		this.taskRegistrar = taskRegistrar;
	}

	/**
	 * 添加任务
	 * 
	 * @param taskId
	 * @param taskName
	 * @param triggerTask
	 * @throws Exception
	 */
	public void addTriggerTask(Integer taskId, String taskName, TriggerTask triggerTask) throws Exception {
		if (this.taskFutures.containsKey(taskId)) {
			throw new Exception("任务调度【" + taskName + "】已存在！");
		}
		TaskScheduler scheduler = this.taskRegistrar.getScheduler();
		ScheduledFuture<?> future = scheduler.schedule(triggerTask.getRunnable(), triggerTask.getTrigger());
		this.taskFutures.put(taskId, future);
		log.info("任务调度【" + taskName + "】添加成功！");
	}

	/**
	 * 取消任务
	 * 
	 * @param taskId
	 * @param taskName
	 * @throws NoSuchFieldException
	 */
	public void cancelTriggerTask(Integer taskId, String taskName) throws NoSuchFieldException {
		ScheduledFuture<?> future = this.taskFutures.get(taskId);
		if (future != null) {
			future.cancel(true);
			this.taskFutures.remove(taskId);
			log.info("任务调度【" + taskName + "】移除成功！");
		}
	}

	/**
	 * 重置任务
	 * 
	 * @param taskId
	 * @param triggerTask
	 * @throws Exception
	 */
	public void resetTriggerTask(Integer taskId, String taskName, TriggerTask triggerTask) throws Exception {
		cancelTriggerTask(taskId, taskName);
		addTriggerTask(taskId, taskName, triggerTask);
		log.info("任务调度【" + taskId + "】重置成功！");
	}

	/**
	 * 任务编号
	 * 
	 * @return
	 */
	public Set<Integer> taskIds() {
		return this.taskFutures.keySet();
	}

	/**
	 * 是否存在任务
	 * 
	 * @param taskId
	 * @return
	 */
	public boolean hasTask(String taskId) {
		return this.taskFutures.containsKey(taskId);
	}

	/**
	 * 任务调度是否已经初始化完成
	 * 
	 * @return
	 */
	public boolean inited() {
		return this.taskRegistrar != null && this.taskRegistrar.getScheduler() != null;
	}
}